package com.clusterswisdom.horn.api.push;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;

import com.alibaba.fastjson.JSONException;

public class ResfulApi {
	
	public static final String ENCODING = "UTF-8";
	 
	private String uuid;
	
	private String sessionId;

	public final String getUuid() {
		return uuid;
	}
	
	public String login(String action, String param) throws IOException {
		HttpURLConnection conn = getConnnection(action);
		conn.setDoOutput(true);
		conn.setRequestMethod("POST");
		if (param != null) {
			conn.setDoOutput(true);
		}
		conn.connect();  
		
		BufferedWriter out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), ENCODING));  
		out.write(param);
		out.flush();  
		out.close();
    	
	    String result = readConnResult(conn);
	    String session_value = conn.getHeaderField("Set-Cookie");
		if (session_value != null && session_value.length() > 0) {
			sessionId = session_value.split(";")[0];
		}
		
	    conn.disconnect();
	    return result;
	}

	public String uploadFile(String type, File file) throws IOException, JSONException {
		if (!file.exists()) {
			throw new IOException("file " + file.getName() + " not exists");
		}
		
		String fileName = file.getName();
		String name = getName(fileName);
		
		String BOUNDARY = "---------------------------7d4a6d158c9"; // 
		StringBuffer sb = new StringBuffer();  
        sb.append("--" + BOUNDARY + "\r\n");
        sb.append("Content-Disposition: form-data; name=\"").append(name).append("\"; filename=\"").append(fileName).append("\"\r\n");  
        sb.append("Content-Type: application/octet-stream\r\n\r\n");  
        
    	HttpURLConnection conn = getConnnection("?type=" + type);
		conn.setDoOutput(true);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("accept-charset", "UTF-8");
		conn.setDoOutput(true);
        byte[] data = sb.toString().getBytes();  
        byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();  
          
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary="+BOUNDARY); 
        conn.setRequestProperty("Content-Length", String.valueOf(data.length + file.length() + end_data.length));   
        
        conn.connect();
        OutputStream os = conn.getOutputStream();
        os.write(data); 
        os.flush();
        FileInputStream fis = new FileInputStream(file);
          
        int rn2 = -1;  
        byte[] buf2 = new byte[1024];  
        while((rn2=fis.read(buf2, 0, 1024))>0) {     
            os.write(buf2, 0, rn2);
            os.flush();
        }  

        os.write(end_data);  
        os.flush();  
        os.close();  
        fis.close();  
          
        String result = readConnResult(conn);
	    conn.disconnect();
	    return result;
	}
	
	public String sendNormalRequest(String url, String param) throws IOException {
		HttpURLConnection conn = getConnnection(url);
		conn.setDoOutput(true);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("accept-charset", "UTF-8");
		if (param != null) {
			conn.setDoOutput(true);
		}
		conn.connect();  
		
		if (param != null) {
			BufferedWriter out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), ENCODING));  
		    out.write(param);
		    out.flush();  
		    out.close();
		}
    	
	    String result = readConnResult(conn);
	    conn.disconnect();
	    return result;
	}
	
	
	public HttpURLConnection openCometConnnection(String url) throws IOException {
		HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(url).openConnection();  
		httpURLConnection.setRequestProperty("Cookie", sessionId);
		httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
		httpURLConnection.setReadTimeout(1800000);
		httpURLConnection.setDoInput(true);
		httpURLConnection.connect();  
		
		return httpURLConnection;
	}
	
	public String getSessionId() {
		return sessionId;
	}
	
	private String readConnResult(HttpURLConnection conn) throws IOException {
	    InputStream in = conn.getInputStream();
	    ByteBuffer buffer = ByteBuffer.allocate(1048576);
	    byte[] bytes = new byte[10240];
	    int len = -1;
	    int size = 0;
	    while ((len = in.read(bytes)) != -1) {
	    	size += len;
	    	buffer.put(bytes, 0, len);
	    }
	    in.close();
	    
	   return new String(buffer.array(), 0, size, ENCODING);
	}
	
	private HttpURLConnection getConnnection(String url) throws IOException {
		HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(url).openConnection();  
		httpURLConnection.setDoInput(true);
		httpURLConnection.setConnectTimeout(60000);
		httpURLConnection.setReadTimeout(60000);
		return httpURLConnection;
	}
	
	private String getName(String fileName) {
		int index = fileName.lastIndexOf(".");
		if (index > 0) {
			return fileName.substring(0, index);
			
		} else {
			return fileName;
			
		}
	}
}